const { eventHub } = require('../event-hub');

/**
 * @type MessageSubscriber
 */
let ipcSubscriber;

/**
 * @type MessagePublisher
 */
let ipcPublisher;
async function initIpcSubscriber() {
  if (!ipcSubscriber) {
    const MessageSubscriber = require('./pub-sub/subscriber');
    ipcSubscriber = new MessageSubscriber('ex_ipc');
    await ipcSubscriber.initQueue();
    await ipcSubscriber.subscribe('broadcast');
    ipcSubscriber.on('message', (routingKey, msg) => {
      const message = JSON.parse(msg);
      // console.log(message);
      const { event, data } = message;
      eventHub.emit(event, data);
    });
  }
}

async function initIpcPublisher() {
  if (!ipcPublisher) {
    const { MessagePublisher } = require('./pub-sub/publisher');
    ipcPublisher = new MessagePublisher('ex_ipc');
    await ipcPublisher.initExchange();
  }
}

/**
 * ipc广播
 * @param {eventKind} event
 * @param {any} data
 * @returns {Promise<any>}
 */
async function broadcast(event, data) {
  return ipcPublisher.publish('broadcast', JSON.stringify({
    event,
    data,
  }));
}

module.exports = {
  initIpcPublisher,
  initIpcSubscriber,

  broadcast,
};
